const db = require('../db/db-connectivity')
const { secret } = require('../utils/config')
const crypto = require('crypto')
module.exports = {
  // 获取用户信息
  getUser: async (req, res) => {
    const username = 'admin'
    const sqlStr = 'select nickname,user_img from shop_users where username =?'
    try {
      const [data] = await db.query(sqlStr, username)
      res.json(...data).end()
    } catch (error) {
      console.log(error)
    }

    // console.log(data)
  },
  /**
   *  增加商品
   *
   *  格式：
   *  const good_name = '汤粉3'
   *  const good_price = {
   *   l: '15',
   *   n: '12',
   *   s: '10',
   *  }
   *  const good_img =
   *   'https://img13.360buyimg.com/n7/jfs/t1/175363/20/23664/176406/61b7fe8bE0bcb2380/a92c4ab45791edd6.jpg'
   *  const good_category = 1
   */
  addGoods: async (req, res) => {
    const form = req.body.form

    //接受表单传过来的数据
    const good_name = form.name
    const good_price = { s: form.s, n: form.n, l: form.l }
    const good_img = form.img
    const good_category = form.category

    const sqlStr = 'select * from goods where good_name =?'
    const sqlStr2 = 'insert into goods SET ?'

    try {
      const [selectRes] = await db.query(sqlStr, good_name)
      console.log(selectRes.length)
      if (selectRes.length === 0) {
        const [insertRes] = await db.query(sqlStr2, {
          good_name: good_name,
          good_price: JSON.stringify(good_price),
          good_img: good_img,
          good_category: good_category,
        })
        console.log(insertRes)
        return res.send('商品已添加')
      }
      return res.send('同商品名已存在')
    } catch (error) {
      console.log(error)
      res.send('添加出错')
    }
  },

  //删除商品
  deleteGoodsByName: async (req, res) => {
    //获取请求的路径的参数
    //进行删除，受影响行不为0则代表删除成功
    const { good_name } = req.body
    const deleteSqlStr = 'DELETE FROM goods WHERE good_name = ?'

    try {
      const [deleteRes] = await db.query(deleteSqlStr, good_name)
      if (deleteRes.affectedRows !== 0) {
        await db.query('alter table goods drop good_id')
        await db.query(
          'alter table goods add good_id int not null primary key auto_increment first;'
        )
        return res.send('已删除商品信息')
      }
      return res.status(204).end()
    } catch (error) {
      console.log('删除出错')
      res.send('删除出错')
    }
  },

  //更改商品信息
  upDateGoodsByID: async (req, res) => {
    const form = req.body.form
    const name = form.name
    const prices = { s: form.s, n: form.n, l: form.l }
    const img = form.img
    const category = form.category
    const sqlStr =
      'update goods set good_name = ?, good_price = ?, good_img = ?, good_category = ? where good_id =?'
    try {
      const [updateRes] = await db.execute(sqlStr, [
        name,
        prices,
        img,
        category,
        form.id,
      ])
      console.log(updateRes)
    } catch (error) {
      console.log('删除不成功')
      return res.send('删除不成功')
    }
    res.send('改变商品信息')
  },
  /**
   * 查询订单
   */
  getOrders: async (req, res) => {
    const sqlStr = 'select * from ordering order by id desc'
    try {
      const [results] = await db.query(sqlStr)
      res.json({ orders: results }).end()
    } catch (error) {
      console.log(error)
      res.send(404)
    }
  },
  deleteOrders: async (req, res) => {
    const { orderId } = req.body
    const deleteSqlStr = 'DELETE FROM ordering WHERE Id = ?'
    try {
      const [deleteRes] = await db.execute(deleteSqlStr, [orderId])
      if (deleteRes.affectedRows !== 0) {
        await db.query('alter table ordering drop Id')
        await db.query(
          'alter table ordering add Id int not null primary key auto_increment first;'
        )
        return res.send('已删除商品信息')
      }
      return res.status(204).end()
    } catch (error) {
      console.log('删除出错')
      res.send('删除出错')
    }
  },
  notifyOrder: (req, res) => {
    res.header({
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
    })
    const sqlStr = 'select * from ordering order by id desc'
    setInterval(async () => {
      try {
        const [results] = await db.query(sqlStr)
        res.write('data:' + JSON.stringify(results) + '\n\n')
      } catch (error) {
        console.log(error)
      }
    }, 3000)
  },
  changePws: async(req, res) => {
    const psw = req.body.psw
    const sqlStr = "select password from shop_users where username='admin'"
    const hash = crypto
      .createHmac('sha256', secret)
      .update('admin' + psw.oldpass + '另一个私钥')
      .digest('hex')

    try {
      const [results] = await db.query(sqlStr)
      // console.log(results[0].password);
      if (results[0].password === hash) {
        const sqlStr2 = "update shop_users set password = ? where username ='admin'"
        const newpsw = crypto
          .createHmac('sha256', secret)
          .update('admin' + psw.passnew + '另一个私钥')
          .digest('hex')
        await db.execute(sqlStr2, [newpsw])
        return res.status(200).end()
      }
      return res.status(500).end()
    } catch (error) {
      console.log('出错');
      res.send(500)
    }
  },
}
